package logic

import (
	"context"
	"fmt"
	"work_srv/cache"
	"work_srv/models"

	"work_srv/internal/svc"
	"work_srv/work"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *work.LoginRequest) (*work.LoginResponse, error) {
	// todo: add your logic here and delete this line
	users := models.User{
		Phone:    in.Phone,
		Password: in.Password,
	}
	models.DB.Debug().Where("phone=?", in.Phone).Find(&users)
	if users.ID == 0 {
		models.DB.Create(&users)
		return nil, fmt.Errorf("用户不存在,系统将自动创建")
	}
	if users.Password != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Phone).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("验证码不正确")
	}
	return &work.LoginResponse{
		Id: int64(users.ID),
	}, nil
}
